<!-- 提现记录 -->

<script setup lang="tsx">
import { ref, inject, computed } from 'vue';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { CheckIcon, CloseIcon, SearchIcon } from 'tdesign-icons-vue-next';
import { getList, getInfo, edit, batch, thirdAgency } from '@/api/bank/presentRecord';
import { getPayList } from '@/api/system/pay';
import { getIP } from '@/api/member/memberAdmin';
import { getChannelList } from '@/api/bank/rechargeChannel';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const data = ref([]);
const columns = [
  {
    colKey: 'row-select',
    type: 'multiple' as const,
    width: 60,
    checkProps: ({ row }: { row: any }) => ({ disabled: row.status != 3 }),
  },
  {
    title: '订单号',
    colKey: 'orderNumber',
    width: 120,
    ellipsis: true,
  },
  {
    title: '财务',
    colKey: 'finance',
  },
  {
    title: '账号',
    colKey: 'userName',
  },
  {
    title: '代理',
    colKey: 'team',
  },
  {
    title: '会员等级',
    colKey: 'vipLevel',
  },
  {
    title: '风险账户',
    colKey: 'danger',
  },
  {
    title: '取款银行',
    colKey: 'bankName',
  },
  {
    title: '取款卡号',
    colKey: 'cardNumber',
  },
  {
    title: '通道',
    colKey: 'payChannel',
  },
  {
    title: '是否首次提现',
    colKey: 'firstTime',
    width: 120,
  },
  {
    title: '信用分',
    colKey: 'credit',
  },
  {
    title: '状态',
    colKey: 'status',
  },
  {
    title: '提交时间',
    colKey: 'submittedTime',
    width: 200,
  },
  {
    title: '用户备注',
    colKey: 'remark',
  },
  {
    title: '取款金额',
    colKey: 'price',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.price || 0);
    },
  },
  {
    title: '换算U',
    colKey: 'usdt',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.usdt || 0);
    },
  },
  {
    title: '处理时间',
    colKey: 'operateTime',
    width: 200,
  },
  {
    title: '操作',
    colKey: 'op',
    width: 120,
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  userType: string | null;
  vipLevel: string | null;
  taskId: string | null;
  type: string | null;
  userName: string | null;
  danger: string | number | null;
  status: string | number | null;
  payChannel: string | number | null;
  cardNumber: string | number | null;
  team: string | number | null;
  orderNumber: string | number | null;
  bankName: string | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  userType: undefined,
  vipLevel: undefined,
  taskId: undefined,
  type: undefined,
  userName: undefined,
  danger: undefined,
  status: undefined,
  payChannel: undefined,
  cardNumber: undefined,
  team: undefined,
  orderNumber: undefined,
  bankName: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);

const footData = computed(() => {
  const totalMoney = data.value.reduce((sum, item) => sum + (item.price || 0), 0);
  const totalUsdt = data.value.reduce((sum, item) => sum + (item.usdt || 0), 0);

  return [
    {
      'row-select': '合计',
      // 格式化显示
      price: new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(totalMoney),
      usdt: new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(totalUsdt),
    },
  ];
});

// 通道列表
const channelList = ref([]);
const unGetChannelList = async () => {
  try {
    const res = await getChannelList({
      pageNum: 1,
      pageSize: 999,
    });
    channelList.value = res.rows;
  } catch (e) {
    console.log(e);
  }
};
unGetChannelList();

// 支付方式列表
const payList = ref([]);
const unGetPayist = async () => {
  try {
    const res = await getPayList({
      pageNum: 1,
      pageSize: 999,
    });
    payList.value = res.rows;
  } catch (e) {
    console.log(e);
  }
};
unGetPayist();

const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <CheckIcon />} onClick={() => changeType(deleteId.value, '1')}>
        审核通过
      </t-button>
      <t-button theme="danger" icon={() => <CloseIcon />} onClick={() => changeType(deleteId.value, '2')}>
        审核未通过
      </t-button>
      {payList.value?.map((item) => <t-button onClick={() => unThirdAgency(deleteId.value, item.payMethod)}>{item.payMethod}批量代付</t-button>)}
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.userName} placeholder="取款账号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.orderNumber} placeholder="订单号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.team} placeholder="代理账号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.cardNumber} placeholder="取款卡号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-select v-model={queryForm.value.vipLevel} placeholder="会员等级">
        {gradeList.value?.map((item) => <t-option key={item.grade} label={item.name} value={item.grade} />)}
      </t-select>
      <t-select v-model={queryForm.value.userType} placeholder="账户类型">
        <t-option key="Agency" label="代理" value="Agency" />
        <t-option key="Member" label="会员" value="Member" />
        <t-option key="Test" label="测试" value="Test" />
      </t-select>
      <t-select v-model={queryForm.value.status} placeholder="状态">
        <t-option key={1} label="成功" value={1} />
        <t-option key={2} label="失败" value={2} />
        <t-option key={3} label="处理中" value={3} />
      </t-select>
      <t-select v-model={queryForm.value.payChannel} placeholder="通道">
        {channelList.value?.map((item) => <t-option key={item.rcId} label={item.name} value={item.rcId} />)}
      </t-select>
      <t-select v-model={queryForm.value.bankName} placeholder="取款银行">
        <t-option key="MTN MoMo" label="MTN MoMo" value="MTN MoMo" />
        <t-option key="Orange Money" label="Orange Money" value="Orange Money" />
      </t-select>
      <t-select v-model={queryForm.value.danger} placeholder="风险账户">
        <t-option key={1} label="是" value={1} />
        <t-option key={0} label="否" value={0} />
      </t-select>
      <t-date-range-picker v-model={dateRange.value} placeholder="提交时间" />
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      v-model:selectedRowKeys={deleteId.value}
      rowKey="id"
      onUnGetList={unGetList}
      footData={footData.value}
    >
      {{
        danger: (slotProps: any) => (
          <div
            style={{
              color: slotProps.row.danger == 1 ? 'red' : '',
            }}
          >
            {slotProps.row.danger == 1 ? '是' : '否'}
          </div>
        ),
        firstTime: (slotProps: any) => (
          <div
            style={{
              color: slotProps.row.firstTime == 1 ? 'red' : '',
            }}
          >
            {slotProps.row.firstTime == 1 ? '是' : '否'}
          </div>
        ),
        status: (slotProps: any) => (
          <t-tag
            variant="light"
            theme={slotProps.row.status == 1 ? 'success' : slotProps.row.status == 2 ? 'danger' : 'warning'}
          >
            {slotProps.row.status == 3 && '处理中'}
            {slotProps.row.status == 1 && '成功'}
            {slotProps.row.status == 2 && '失败'}
          </t-tag>
        ),
        op: (slotProps: any) => (
          <Space>
            {slotProps.row.status == 3 ? (
              <Link theme="warning" onClick={() => unEdit(slotProps, '审核')}>
                审核
              </Link>
            ) : (
              <Link theme="primary" onClick={() => unEdit(slotProps, '详情')}>
                详情
              </Link>
            )}
            <Link theme="danger" onClick={() => unIpCheck(slotProps)}>
              IP检测
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

// 等级列表
import { useGradeStore } from '@/store/modules/member';
const gradeStore = useGradeStore();
const gradeList = ref<any[]>([]);
gradeList.value = gradeStore.gradeList;

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};
unGetList();
const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  dateRange.value = [];
  unGetList();
};

/** 批量对话框 */
const header = ref('确认通过当前所选订单？');
const body = ref('点击后将通过所选订单，是否继续？');
const type = ref('1');

// 不通过
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value;
  let status = type.value;
  // type 1 通过 2 不通过
  batch({ ids, status }).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('操作成功');
    deleteId.value = [];
    unGetList();
  });
};

const changeType = (value: any, onType: string) => {
  if (!value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  const confirmText = onType == '1' ? '通过' : '不通过';
  header.value = `确认${confirmText}当前所选订单？`;
  body.value = `点击后将${confirmText}所选订单，是否继续？`;
  type.value = onType;
  confirmVisible.value = true;
  deleteId.value = value;
};

/** 单个审核对话框 */
const formObj = new formGroup();
const unEdit = async (slotProps: any, test: string) => {
  try {
    let res = await getInfo(slotProps.row.id);
    if (test == '审核') {
      formObj.show(
        '提现处理',
        {
          ...res.data,
        },
        '提现处理',
      );
    } else {
      formObj.show(
        '详情',
        {
          ...res.data,
        },
        '详情',
      );
    }
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '提现处理',
  '提现处理',
  {},
  async (body) => {
    await edit(body.data);
    deleteId.value = [];
    unGetList();
  },
  {},
);

formObj.add<any>('详情', '详情', {}, undefined, {});

// 三方代付
const confirmVisible2 = ref(false);
const onConfirmThirdAgency = () => {
  let ids = deleteId.value;
  let platform = type.value;
  thirdAgency({ ids, platform }).then(() => {
    confirmVisible2.value = false;
    MessagePlugin.success('操作成功');
    deleteId.value = [];
    unGetList();
  });
};

const unThirdAgency = (value: any, code: string) => {
  if (!value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  header.value = `确认使用${code}代付当前所选订单？`;
  body.value = `点击后将使用${code}代付所选订单，是否继续？`;
  type.value = code;
  confirmVisible2.value = true;
  deleteId.value = value;
};

// IP检测
const unIpCheck = async (slotProps: any) => {
  try {
    let res = await getIP(slotProps.row.uid);
    formObj.show(
      'IP检测',
      {
        ...res.data,
      },
      'IP检测',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>('IP检测', 'IP检测', {}, undefined, {});
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 编辑任务对话框 -->
        <template v-if="item == '提现处理' || item == '详情'">
          <t-form-item label="订单编号" name="orderNumber">
            <t-input v-model="formData.orderNumber" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="提款金额" name="price">
            <t-input v-model="formData.price" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="提款信息" name="remark">
            <t-textarea v-model="formData.remark" readonly placeholder="提款信息" :autosize="{ minRows: 5 }" />
          </t-form-item>
          <t-form-item label="处理结果" name="status">
            <t-radio-group v-model="formData.status" :readonly="item == '详情'">
              <t-radio :value="1">成功</t-radio>
              <t-radio :value="2">失败</t-radio>
              <t-radio :value="3">处理中</t-radio>
            </t-radio-group>
          </t-form-item>
          <t-form-item label="处理说明" name="explanation">
            <t-textarea v-model="formData.explanation" :readonly="item == '详情'" placeholder="处理说明"
              :autosize="{ minRows: 3 }" />
          </t-form-item>
        </template>
        <!-- IP检测对话框 -->
        <template v-if="item == 'IP检测'">
          <t-form-item label="账户" name="username">
            <t-input v-model="formData.username" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="登录IP" name="lastIp">
            <t-input v-model="formData.lastIp" readonly placeholder=" " />
          </t-form-item>
          <t-form-item label="同IP账户数" name="sameIpUserCount" help="包括自己">
            <t-input v-model="formData.sameIpUserCount" readonly placeholder=" " />
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
    <t-dialog v-model:visible="confirmVisible" :header="header" :body="body" @confirm="onConfirmDelete" />
    <t-dialog v-model:visible="confirmVisible2" :header="header" :body="body" @confirm="onConfirmThirdAgency" />
  </div>
</template>
